﻿using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;

using System.Text.RegularExpressions;

using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace pnh
{
    static class Extract
    {

        public static JSONData extractAchievements(string input)
        {
            string pattern = @"broker\.publish\(routes\.activity\.details\.load, (.*)?\);";
            Match resultRegex = Regex.Match(input, pattern);

            if (resultRegex.Groups.Count < 2)
                return null;


            //the result to returl
            JSONData ret = new JSONData();

            //get the json object
            JObject obj = (JObject)JsonConvert.DeserializeObject(resultRegex.Groups[1].Value);

            //get the array of players
            JArray ArrayPlayers = (JArray)obj["Players"];

            //get the first player (the one we scrape)
            JObject player = (JObject)ArrayPlayers[0];

            //store player info
            JSONPlayer jPlayer = new JSONPlayer();
            jPlayer.Gamertag = (string)player["Gamertag"];
            jPlayer.Gamerpic = (string)player["Gamerpic"];
            jPlayer.Gamerscore = (int)player["Gamerscore"];
            jPlayer.GameCount = (int)player["GameCount"];
            jPlayer.PercentComplete = (int)player["PercentComplete"];
            ret._player = jPlayer;

            JArray ArrayAchievements = (JArray)obj["Achievements"];

            int acheCount = ArrayAchievements.Count;
            JSONAchievement[] jArrayAche = new JSONAchievement[acheCount];

            //foreach (JObject ache in ArrayAchievements)
            for (int i = 0; i < acheCount; ++i)
            {
                JObject ache = (JObject)ArrayAchievements[i];

                JSONAchievement jAche = new JSONAchievement();
                jAche.Id = (int)ache["Id"];
                jAche.TileUrl = (string)ache["TileUrl"];
                jAche.Name = (string)ache["Name"];
                jAche.Description = (string)ache["Description"];
                jAche.Score = (int)ache["Score"];
                jAche.IsHidden = (bool)ache["IsHidden"];
                jAche.Unlocked = false;

                JObject earnedDate = (JObject)ache["EarnDates"];
                JObject earnedDatePlayer = (JObject)earnedDate[jPlayer.Gamertag];
                if (earnedDatePlayer != null)
                {
                    jAche.EarnedOn = (DateTime)earnedDatePlayer["EarnedOn"];
                    jAche.IsOffline = (bool)earnedDatePlayer["IsOffline"];
                    jAche.Unlocked = true;
                }

                jArrayAche[i] = jAche;

            }
            ret._achievements = jArrayAche;

            return ret;
        }
    }
}
